package com.xbongbong.pro.dataset.helper;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.FieldAttrConstant;
import com.xbongbong.paas.constant.XbbConstant;
import com.xbongbong.paas.domain.entity.ext.CkPaasFormDataEntityExt;
import com.xbongbong.paas.enums.BIProductReformEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.bi.XbbTableRefEnum;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.bi.commons.sql.SqlBuilderHandler;
import com.xbongbong.pro.statistic.constant.RelatedProductConstant;
import com.xbongbong.pro.statistics.help.InitSqlHelper;
import com.xbongbong.pro.statistics.service.StarDataService;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author  gzt
 * @Description 关联产品处理公共类
 * @Date 17:20 2022/11/11

 **/
@Slf4j
@Component
public class RelatedProductHelper {
    @Resource
    private StarDataService starDataService;
    /**
     * 获取关联产品最新的名称和编号
     * @param corpid
     * @param tableHeadArr 表头
     * @param  businessType
     * @param resultArr 数据结果
     * @throws
     * @author xinpeng.jiang
     * @date 2022/1/25 19:07
     * @version 1.0
     */
    public void getNewProduct(String corpid, JSONArray tableHeadArr, Integer businessType, JSONArray resultArr, String relProductAttr) {
        if (!BIProductReformEnum.getProductSubBusList().contains(businessType) || CollectionsUtil.isEmpty(resultArr)) {
            return;
        }
        StringBuilder column = new StringBuilder(ParameterConstant.ID);
        boolean isSelectName = false;
        String productNameAttr = "";
        boolean isSelectNo = false;
        String productNoAttr = "";
        // 判断是否选了产品名称或者产品编号
        for (int i = 0; i < tableHeadArr.size(); i++) {
            JSONObject tableHead = tableHeadArr.getJSONObject(i);
            if ((StringUtils.isEmpty(relProductAttr) && Objects.equals(SelectProductEnum.PRODUCT.getAttr(), tableHead.getString("attr"))) || Objects.equals(tableHead.getString("attr"),relProductAttr)) {
                // 选名称
                isSelectName = true;
                productNameAttr = tableHead.getString("attr");
                //column.append(XbbConstant.SQL_COMMA).append(XbbConstant.JSON_EXTRACT).append(XbbConstant.L_P).append(XbbTableRefEnum.PRODUCT.getTableName()).append(XbbConstant.POINT).append(XbbConstant.DATA).append(XbbConstant.SQL_COMMA).append(InitSqlHelper.format4Text(ProductEnum.NAME.getAttr())).append(MessageFormat.format("{0}{1}{2}{3}", XbbConstant.SQL_COMMA, XbbConstant.SINGLE_QUOTES, XbbConstant.STRING_CONSTANT, XbbConstant.SINGLE_QUOTES)).append(XbbConstant.R_P).append(" AS productName");
                column.append(XbbConstant.SQL_COMMA).append(ProductEnum.NAME.getAttr()).append(" AS productName");
            } else if (Objects.equals(RelatedProductConstant.COMMON_PRODUCT_SERIAL_NO_ATTR, tableHead.getString("attr"))) {
                // 选编号
                isSelectNo = true;
                productNoAttr = tableHead.getString("attr");
                //column.append(XbbConstant.SQL_COMMA).append(XbbConstant.JSON_EXTRACT).append(XbbConstant.L_P).append(XbbTableRefEnum.PRODUCT.getTableName()).append(XbbConstant.POINT).append(XbbConstant.DATA).append(XbbConstant.SQL_COMMA).append(InitSqlHelper.format4Text(ProductEnum.PRODUCT_NO.getAttr())).append(MessageFormat.format("{0}{1}{2}{3}", XbbConstant.SQL_COMMA, XbbConstant.SINGLE_QUOTES, XbbConstant.STRING_CONSTANT, XbbConstant.SINGLE_QUOTES)).append(XbbConstant.R_P).append(" AS productNo");
                column.append(XbbConstant.SQL_COMMA).append(ProductEnum.PRODUCT_NO.getAttr()).append(" AS productNo");
            }
            // 都选了就不用循环了
            if (isSelectName && isSelectNo) {
                break;
            }
        }
        // 选了其中一个就要去查库
        if (isSelectName || isSelectNo) {
            // 获取产品id
            List<Long> productIdList = new ArrayList<>();
            for (int i = 0; i < resultArr.size(); i++) {
                JSONObject resultObj = resultArr.getJSONObject(i);
                if (Objects.nonNull(resultObj)){
                    Long resultObjLong = resultObj.getLong(StringUtil.getDataBaseString(RelatedProductConstant.PRODUCT_ID));
                    if (Objects.isNull(resultObjLong)){
                        resultObjLong = resultObj.getLong(RelatedProductConstant.PRODUCT_ID);
                    }
                    if (Objects.isNull(resultObjLong)){
                        try {
                            //resultObjLong = resultObj.getLong(SelectProductEnum.PRODUCT.getAttr());
                            // 多层处理
                            resultObjLong = resultObj.getLong(relProductAttr);
                        } catch (Exception e) {
                            log.error("关联产品处理",e);
                        }
                    }
                    productIdList.add(resultObjLong);
                }
            }
            // 查库
            SqlBuilderHandler sqlBuilderHandler = SqlBuilderHandler.start();
            sqlBuilderHandler.select(String.valueOf(column)).from(XbbTableRefEnum.PRODUCT.getTableName())
                    .where(ParameterConstant.CORPID).append(XbbConstant.EQUAL).append(InitSqlHelper.format4Text(corpid))
                    .andIn(ParameterConstant.ID,productIdList).andEqual(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            String sql = sqlBuilderHandler.end().getSql();
            List<CkPaasFormDataEntityExt> productResultList = starDataService.findEntitysBySql(sql);
            Map<Long, CkPaasFormDataEntityExt> productResultMap = productResultList.stream().collect(Collectors.toMap(CkPaasFormDataEntityExt::getId, p -> p, (k1, k2) -> k1));
            // 塞回去
            if (CollectionsUtil.isNotEmpty(productResultList)) {
                for (int i = 0; i < resultArr.size(); i++) {
                    JSONObject resultObj = resultArr.getJSONObject(i);
                    if (Objects.isNull(resultObj)){continue;}
                    Long resultObjLong = resultObj.getLong(StringUtil.getDataBaseString(RelatedProductConstant.PRODUCT_ID));
                    if (Objects.isNull(resultObjLong)){
                        resultObjLong = resultObj.getLong(RelatedProductConstant.PRODUCT_ID);
                    }
                    if (Objects.isNull(resultObjLong)){
                        try {
                            //resultObjLong = resultObj.getLong(SelectProductEnum.PRODUCT.getAttr());
                            resultObjLong = resultObj.getLong(relProductAttr);
                        } catch (Exception e) {
                            log.error("关联产品处理",e);
                        }
                    }
                    CkPaasFormDataEntityExt ckPaasFormDataEntityExt = null;
                    if (Objects.nonNull(resultObjLong)) {
                        ckPaasFormDataEntityExt = productResultMap.getOrDefault(resultObjLong, null);
                    }
                    if (Objects.nonNull(ckPaasFormDataEntityExt)) {
                        if (isSelectName) {
                            resultObj.put(productNameAttr, ckPaasFormDataEntityExt.getProductName());
                        }
                        if (isSelectNo) {
                            resultObj.put(productNoAttr, ckPaasFormDataEntityExt.getProductNo());
                        }
                    }
                }
            }
        }
    }
    /**
     * @author  gzt
     * @Description 关联产品特殊处理
     * @Date 16:24 2022/11/11
     * @param boardJson
     * @param formIdNodeIdMap
     * @param attrRelationProduct
     * @param jsonObject
     * @param inputNodeIdSet
     * @throws
     **/

    public  void handlerRelProduct(JSONObject boardJson, Map<Long, String> formIdNodeIdMap, Map<Long, String> attrRelationProduct, JSONObject jsonObject, Set<String> inputNodeIdSet){
        String attrType = jsonObject.getString("attrType");
        //图表中心渲染attrType为空
        if (StringUtils.isNotEmpty(attrType) && !StringUtils.equals(attrType, StringConstant.TEXT)){
            return;
        }
        Set<Long> longSet = formIdNodeIdMap.keySet();
        String attr =  jsonObject.getString(StringConstant.ATTR);;
        String srcB = jsonObject.getString("srcB");
        if (formIdNodeIdMap.size() == attrRelationProduct.size()){return;}
        if (Objects.nonNull(srcB)){
            Map<String, Object> srcBMap  = JSONObject.parseObject(srcB, Map.class);
            String finalAttr = attr;
            Set<String> keySet = srcBMap.keySet();
            try {
                for (Long aLong : longSet) {
                    String val = formIdNodeIdMap.get(aLong);
                    JSONObject jsonObject1 = (JSONObject)srcBMap.get(val);
                    if (Objects.isNull(jsonObject1)){
                        for (String obj : keySet) {
                            if (!inputNodeIdSet.contains(obj)){
                                JSONObject  node1 = (JSONObject)srcBMap.get(obj);
                                String originalAttr = (String) node1.get(FieldAttrConstant.ORIGINALATTR);
                                handlerRelProduct(boardJson, formIdNodeIdMap, attrRelationProduct, boardJson.getJSONObject(obj).getJSONArray("field"),inputNodeIdSet, finalAttr,originalAttr);
                            }
                        }
                    }else if (Objects.nonNull(jsonObject1) && Objects.equals(SelectProductEnum.PRODUCT.getAttr(),jsonObject1.get(FieldAttrConstant.ORIGINALATTR))){
                        attrRelationProduct.put(aLong, finalAttr);
                        //画布中一种数据源只出现一次，匹配上的关联产品需移除
                    }
                }
            } catch (Exception e) {
                log.error("关联产品处理-handlerRelProduct",e);
            }
        }
    }
    /**
     * @author  gzt
     * @Description 递归调用处理关联产品渲染
     * @Date 17:23 2022/11/11
     * @param boardJson
     * @param formIdNodeIdMap
     * @param attrRelationProduct
     * @param fieldArray
     * @param inputNodeIdSet
     * @param attr
     * @param originalAttr
     * @throws
     **/

    private void handlerRelProduct(JSONObject boardJson, Map<Long, String> formIdNodeIdMap, Map<Long, String> attrRelationProduct, JSONArray fieldArray,Set<String>  inputNodeIdSet,String attr,String originalAttr) {
        int fieldSize = fieldArray.size();
        for (int i = 0; i < fieldSize; i++) {
            /*Arrays.stream(fieldArray.stream().toArray()).filter(obj->Objects.equals(((JSONObject)obj).getString("attr"),originalAttr)).map(obj->{
            })*/
            JSONObject jsonObject = fieldArray.getJSONObject(i);
            if (!Objects.equals(jsonObject.getString(FieldAttrConstant.ATTR),originalAttr)){
                continue;
            }
            if (formIdNodeIdMap.size() == attrRelationProduct.size()){break;}
            Set<Long> longSet = formIdNodeIdMap.keySet();
            String attrType = jsonObject.getString("attrType");
            if (!StringUtils.equals(attrType,StringConstant.TEXT)){
                continue;
            }
            String srcB = jsonObject.getString("srcB");
            if (Objects.nonNull(srcB)){
                Map<String, Object> srcBMap  = JSONObject.parseObject(srcB, Map.class);
                String finalAttr = attr;
                Set<String> keySet = srcBMap.keySet();
                for (Long aLong : longSet) {
                    String val = formIdNodeIdMap.get(aLong);
                    JSONObject jsonObject1 = (JSONObject)srcBMap.get(val);
                    if (Objects.isNull(jsonObject1)){
                        for (String obj : keySet) {
                            if (!inputNodeIdSet.contains(obj)){
                                JSONObject  node1 = (JSONObject)srcBMap.get(obj);
                                String originalAttrC = (String) node1.get(FieldAttrConstant.ORIGINALATTR);
                                handlerRelProduct(boardJson, formIdNodeIdMap, attrRelationProduct, boardJson.getJSONObject(obj).getJSONArray("field"),inputNodeIdSet, finalAttr,originalAttrC);
                            }
                        }
                    }else if (Objects.nonNull(jsonObject1) && Objects.equals(SelectProductEnum.PRODUCT.getAttr(),jsonObject1.get(FieldAttrConstant.ORIGINALATTR))){
                        attrRelationProduct.put(aLong, finalAttr);
                        //画布中一种数据源只出现一次，匹配上的关联产品需移除
                    }
                }
            }
        }
    }
}
